package com.mycache.controller;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUnit;
import com.mycache.cache.LfuCache;
import com.mycache.cache.LruCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author wang.liu
 * @version 1.0
 * @description description
 * @date 9:44 上午 2021/12/12
 */
@Controller
@Slf4j
public class CacheController {
    private final LruCache lruCache;
    private final LfuCache lfuCache;

    public CacheController() {
        lruCache = new LruCache(4);
        lfuCache = new LfuCache(4);
    }

    @RequestMapping("/lru/get")
    @ResponseBody
    public String lruGet(@RequestParam(name = "key") String key) {
        log.info("lruGet--before cache:{}", lruCache.toString());
        String value = lruCache.get(key);
        log.info("lruGet--after cache:{}", lruCache.toString());
        return value;
    }

    @RequestMapping("/lru/put")
    @ResponseBody
    public String lruPut(@RequestParam(name = "key") String key, @RequestParam(name = "value") String value) {
        log.info("lruPut--before cache:{}", lruCache.toString());
        lruCache.put(key, value);
        log.info("lruPut--after cache:{}", lruCache.toString());
        return value;
    }

    @RequestMapping("/lfu/get")
    @ResponseBody
    public String lfuGet(@RequestParam(name = "key") String key) {
        log.info("lfuGet--before cache:{}", lfuCache.toString());
        String value = lfuCache.get(key);
        log.info("lfuGet--after cache:{}", lfuCache.toString());
        return value;
    }

    @RequestMapping("/lfu/put")
    @ResponseBody
    public String lfuPut(@RequestParam(name = "key") String key, @RequestParam(name = "value") String value) {
        log.info("lfuPut--before cache:{}", lfuCache.toString());
        lfuCache.put(key, value);
        log.info("lfuPut--after cache:{}", lfuCache.toString());
        return value;
    }
    public String hutoolCache(@RequestParam(name = "key") String key, @RequestParam(name = "value") String value) {
        Cache<String, String> lruCache = CacheUtil.newLRUCache(3);
        //通过实例化对象创建
        //LRUCache<String, String> lruCache = new LRUCache<String, String>(3);
        lruCache.put("key1", "value1", DateUnit.SECOND.getMillis() * 3);
        lruCache.put("key2", "value2", DateUnit.SECOND.getMillis() * 3);
        lruCache.put("key3", "value3", DateUnit.SECOND.getMillis() * 3);
        lruCache.get("key1");//使用时间推近
        lruCache.put("key4", "value4", DateUnit.SECOND.getMillis() * 3);

        //由于缓存容量只有3，当加入第四个元素的时候，根据LRU规则，最少使用的将被移除（2被移除）
        String value2 = lruCache.get("key");//null
        return value;
    }

}
